#include "button.h"
#include <Arduino.h>
#include "MyWifi.h"

extern TaskHandle_t gWifiSmartTaskHandle;
unsigned char btnPins[BTN_MAX - 1] = {BTN_WIFI_RESET_PIN,BTN_WIFI_CLEAR_PIN};
static BUTTON_STATE button_res()
{
    for(int i = 0; i < BTN_MAX - 1; i++)
    {
      
      if(digitalRead(btnPins[i]) == LOW) 
      {
        vTaskDelay(10/portTICK_PERIOD_MS);
        if(digitalRead(btnPins[i])==LOW) 
        {
            return (BUTTON_STATE)(i + 1);
        }
      }
    }
    return BTN_NO;
}

static void button_wait_undo(unsigned char pin)
{
    while(digitalRead(pin) == 0)
    {
        vTaskDelay(10/portTICK_PERIOD_MS);
    }
}

void btn_task(void *pvParameters)
{
    BUTTON_STATE btnState = BTN_NO;
    while (1)
    {   
        btnState = button_res();
        if(btnState == BTN_WIFI_RESET)
        {
            Serial.println("press BUTN_WIFI_RESET button");
            xTaskNotifyGive(gWifiSmartTaskHandle);
            button_wait_undo(BTN_WIFI_RESET);
        } 
        else if(btnState == BTN_WIFI_CLEAR)
        {
            Serial.println("press BTN_WIFI_CLEAR button");
            wifi_clear();
            button_wait_undo(BTN_WIFI_CLEAR);
        }
        vTaskDelay(10/portTICK_PERIOD_MS);
    }
}

void btn_init(void)
{
    pinMode(BTN_WIFI_RESET_PIN, INPUT_PULLUP);
    pinMode(BTN_WIFI_CLEAR_PIN, INPUT_PULLUP);
    
}

